//
//  BalanceCheckstandTableViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/8/23.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit

class BalanceCheckstandTableViewController: BaseTableViewController {
    
    @IBOutlet weak var totalMoney: UILabel!
    @IBOutlet weak var balance: UILabel!
    @IBOutlet weak var needMoney: UILabel!
    @IBOutlet weak var moneyNumber: UILabel!
    @IBOutlet weak var alipayImageV: UIImageView!
    @IBOutlet weak var wechatImageV: UIImageView!
    
    lazy var keyBoard:CustomKeyBoard = {
        let view = CustomKeyBoard.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight))
        UIApplication.shared.keyWindow?.addSubview(view)
        view.backInputValue = { [weak self] (value) in
            self?.money = Double.init(value)!
            self?.moneyNumber.text = "\(value)"
        }
        return view
    }()
    
    lazy var rechargeAlertView : AlertContentView = {
        let view = AlertContentView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight))
        UIApplication.shared.keyWindow?.addSubview(view)
        return view
    }()
    
    var payType = 0 //支付方式 0支付宝 1微信
    
    var money:Double = 0
    
    var model:PayBalanceModel!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
        self.title = "收银台"
        self.alipayImageV.isHighlighted = true
        
        self.totalMoney.text = "￥" + self.model.orderMoney
        self.balance.text = "￥" + self.model.userMoney
    
        let str = "¥" + model.money
        var attribute = NSMutableAttributedString.init(string: str)
        attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 11)], range: NSString.init(string: str).range(of: "¥" + model.money))
        attribute = NSMutableAttributedString.init(attributedString: attribute)
        attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 17)], range: NSString.init(string: str).range(of: model.money.getPriceInteger()))
        
        attribute = NSMutableAttributedString.init(attributedString: attribute)
        attribute.addAttributes([NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "#ed4848")], range: NSString.init(string: str).range(of: "¥" + model.money))
        self.needMoney.attributedText = attribute
        
        self.moneyNumber.text = self.model.money
        self.money = Double.init(self.model.money)!
        
        NotificationCenter.default.addObserver(self, selector: #selector(receivePayResult(notification:)), name: NSNotification.Name(rawValue: "rechargeResult"), object: nil)

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.addObserver(self, selector: #selector(receivePayResult(notification:)), name: NSNotification.Name(rawValue: "rechargeResult"), object: nil)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "rechargeResult"), object: nil)
    }
    
    @objc func receivePayResult(notification:Notification){
        
        guard let userInfo = notification.object else {
            return
        }
        if (userInfo as! postParameters)["isSuccess"] as! Bool == true {
            PKhud.showText(text: "充值成功，请继续支付~")
            Utils.DispatchAfter(after: 2) {
                let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "OrderListViewController") as! OrderListViewController
                self.navigationController?.pushViewController(ctrl, animated: true)
            }
        }else{
            self.rechargeAlertView.showRechargeAlert(title: "充值失败", content: (payType == 0 ? "支付宝" : "微信") + "支付失败，本次充值未完成")
        }
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "rechargeResult"), object: nil)
    }
    
    override func backBarButtonMethon() {
        PKhud.hiden()
        self.keyBoard.removeFromSuperview()
        self.navigationController?.popViewController(animated: true)
    }
    
    // MARK:充值
    @IBAction func rechargeMethod(_ sender: UIButton) {
        
        if self.money < (Double.init(self.model.money))! {
            PKhud.showText(text: "充值金额不能小于" + self.model.money)
            return
        }
        
        (UIApplication.shared.delegate as! AppDelegate).type = .recharge
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.payRecharge.rawValue, parameters: ["money":self.money,"payType":self.payType]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                if self.payType == 0 {
                    // 支付宝
                    AlipaySDK.defaultService().payOrder(result["data"] as! String, fromScheme: "zxsupermarket", callback: { (resultDic) in
                        
                    })
                    
                }else{
                    
                    let isInstall = WXApi.isWXAppInstalled()
                    guard isInstall else {
                        PKhud.showText(text: "您尚未安装微信客户端~")
                        return
                    }
                    // 微信
                    if let dic = result["data"] as? postParameters {
                        let request = PayReq.init()
                        request.partnerId = dic["partnerid"] as! String
                        request.prepayId = dic["prepayid"] as! String
                        request.package = dic["package"] as! String
                        request.nonceStr = dic["noncestr"] as! String
                        request.timeStamp = UInt32(dic["timestamp"] as! String)!
                        request.sign = dic["sign"] as! String
                        WXApi.send(request)
                    }
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 3
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if section == 0 {
            return 3
        }else if section == 1{
            return 1
        }else{
            return 2
        }
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 1 {
            self.keyBoard.isHidden = false
            self.keyBoard.show()
            
        }else if indexPath.section == 2 {
            if indexPath.row == 0 {
                self.alipayImageV.isHighlighted = true
                self.wechatImageV.isHighlighted = false
                self.payType = 0
            }else{
                self.alipayImageV.isHighlighted = false
                self.wechatImageV.isHighlighted = true
                self.payType = 1
            }
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0.01
        }else{
            return 43
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section != 0 {
            let header = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 43))
            header.backgroundColor = UIColor.backgroundColor
            
            let titleLabel = Utils.labelWith(frame: CGRect.init(x: 11.5, y: 0, width: UIScreen.ScreenWidth - 11.5, height: 43), font: UIFont.boldSystemFont(ofSize: 14), textAlignment: NSTextAlignment.left, textColor: "000000", text: (section == 1 ? "充值金额" : "支付方式"))
            header.addSubview(titleLabel)
            
            return header
        }else{
            return UIView()
        }
    }

}
